package com.demo.springbootdemo.domain.dto;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.springbootdemo.domain.vo.UserVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@ApiModel("分页结果")
public class PageDTO<T> {

    @ApiModelProperty(value = "当前页码")
    private Long pageNo;

    @ApiModelProperty(value = "分页大小")
    private Long pageSize;

    @ApiModelProperty(value = "记录总数")
    private Long total;

    @ApiModelProperty(value = "总页数")
    private Long pages;

    @ApiModelProperty(value = "结果列表")
    private List<T> list;

    public static <VO, PO> PageDTO<VO> of(Page<PO> page, Class<VO> clazz) {
        PageDTO<VO> result = new PageDTO<>();

        result.setPageNo(page.getCurrent());
        result.setPageSize(page.getSize());
        result.setTotal(page.getTotal());
        result.setPages(page.getPages());
        result.setList(BeanUtil.copyToList(page.getRecords(), clazz));

        return result;
    }

    public static <VO, PO> PageDTO<VO> of(Page<PO> page, Function<PO, VO> convertor) {
        PageDTO<VO> result = new PageDTO<>();

        result.setPageNo(page.getCurrent());
        result.setPageSize(page.getSize());
        result.setTotal(page.getTotal());
        result.setPages(page.getPages());
        List<PO> list = page.getRecords();
        result.setList(list.stream().map(convertor).collect(Collectors.toList()));

        return result;
    }
}
